Interpolating data with polynomials using Matlab

Interpolating data points involves selecting a function such that . Common functions to use are polynomials.

It can be proven mathematically that given N+1 data points with distinct domain values, there is a unique polynomial of degree N that passes through all the data points. Using polynomials can work adequately if there are only a few data points, such as 3 to 5. For instance, a quadratic polynomial will exactly pass through 3 data points and a cubic polynomial will pass through 4 data points. However, if there are many data points, such as 15-20, then interpolating with a 14-19 degree polynomial will satisfy the mathematical requirement that the function pass through all points, but the function itself behaves badly between data points.

A more common practice is to approximate many data points with a polynomial of low degree such as a linear function. In this case the line comes close to the data but does not pass through the data points. This is usually because data is scattered from the exact functional form due to measuring errors or statistical fluctuations in the data itself.

Matlab conveniently computes the coefficients of a polynomial that passes through a set of data points. If x and y are vectors of 5 data values entered into Matlab, then the function polyfit

a = polyfit(x,y,4);

returns the coefficients of a polynomial of degree 4 that passes through the 5 data points in vectors x and y. The variable a is a vector of length 5 that holds the coefficients

With these coefficients a fourth degree polynomial for instance could be written in Matlab as

a(1)*x^4 + a(2)*x^3 + a(3)*x^2 + a(4)*x + a(5)

However, Matlab has a more convenient way to evaluate a polynomial with coefficients computed by polyfit. This is with a companion function called polyval.

y_values = polyval(a, x_values);

If x_values is a vector of x values, then the polyval function uses the coefficients in the "a" vector to compute the value of the polynomial at each of the x values and returns these results to the vector y_values.

Similarly if the degree of the fitting polynomial is less than N, when there are N+1 data points, then polyfit and polyval commands will approximate the data points with a polynomial of lower degree. For instance, to approximate the data with a linear function

c = polyfit(x,y,1);
y_values = polyval(c,x_values);